"""
    @author: Jean-Lou Dupont
"""
import os
import sys
import logging
import string

from string import Template
from datetime import datetime

from google.appengine.api import users

from libs.tagrate.post  import TagRatePost

class AtomFeed(object):
    
        def generateAtomFeed(self, user, link, liste, reverse):
            """
                @return: 'modified date' of the last entry 
            """
        
            entries = self.generateAtomEntryList( user, liste, reverse )
            
            params = { 
                "title":    user.nickname()+' - TagRate Feed',
                "link":     link,
                "feedlink": link,
                "updated":  "",    #TODO last generated ??
                "author":   user.nickname(),
                "id":       link,
                "entries":  entries
            }
            channel = self.generateAtomChannel(params)
            
            if liste:
                last_modified = liste[0]
            else:
                last_modified = None
            
            return ( str( channel ), last_modified )

        def generateAtomChannel(self, params):
            tpl = Template( _AtomFeedChannel )
            return str( tpl.substitute( params ) )
        
        def generateAtomEntryList(self, user, liste, reverse ):
            """
                DateTime entries must be formatted
                according to RFC3339 using  $date T $time
            """
            #========== FEED ======= POST ======
            _mapper = {
                        'title':    'title',
                        'link' :    'url',
                        'updated':  'modified',
                        'published':'created',
                        'content':  'notes'
                        #'id':       'key'
            }
            _dates  = {
                       'updated':   True,
                       'published': True
            }
            
            #liste = TagRatePost.defaultList( user )
            if not liste:
                return None
    
            if reverse:
                liste.reverse()
    
            #logging.info('generateAtomEntryList: list AVAILABLE')
            entries = ''
            tpl = Template( _AtomFeedEntry )
            for entry in liste:
                #tpl = Template( _AtomFeedEntry )
                params = {}
                for inFeedKey in _mapper:
                    inPostKey = _mapper[ inFeedKey ]
                    
                    try:    value = getattr( entry , inPostKey )
                    except: value = ''
                        
                    try:    isDateTime = _dates[inFeedKey]
                    except: isDateTime = False
                        
                    if isDateTime is True:
                        value = self.formatToRFC3339_DateTime( value )
                        
                    params[inFeedKey] = value
                    
                params['id'] = entry.key()
                entries += tpl.substitute( params )
            
            return entries
        
        def formatToRFC3339_DateTime(self, input):
            """
                example: 2008-09-10T09:44:23.995-07:00
                @todo fix timezone...
            """
            date = str( input.date() )
            time = str( input.time() )
            return date+'T'+time+'-00:00'   
        
#========================================================================================================

#@see http://tools.ietf.org/html/rfc4287
_AtomFeedChannel = """<?xml version="1.0" encoding="utf-8"?>
   <feed xmlns="http://www.w3.org/2005/Atom">

     <title>$title</title>
     <link href="$link"/>
     <link rel="self" type="application/atom+xml" href="$feedlink"/>
     <updated>$updated</updated>
     <author>
       <name>$author</name>
     </author>
     <id>$id</id>

    $entries
    
   </feed>
"""

_AtomFeedEntry = """
    <entry>
       <title>$title</title>
       <id>$id</id>
       <link rel='alternate' type='text/html' href='$link'/>
       <updated>$updated</updated>
       <published>$updated</published>
       <content type="html">
       $content
       </content>
     </entry>
"""
